package com.erpanderp.wam.asset.model.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;

import com.erpanderp.wam.asset.model.entity.AssetHistory;
import com.erpanderp.wam.util.HibernateUtil;

public class AssetHistoryDAO { 
	
	public AssetHistory saveOrUpdateAssetHistory(AssetHistory assetHistory) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.getTransaction().begin();
			System.out.println("FLUSH MODE: " + session.getFlushMode());
			session.setFlushMode(FlushMode.COMMIT);
			session.saveOrUpdate(assetHistory);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return assetHistory;
	}	
	
	public List<AssetHistory> getAssetHistoryDetailsByAssetRequest(Long assetRequestId){
		System.out.println("=====assetRequestId====DAO======="+assetRequestId);
		List<AssetHistory> assetHistoryDetails = new ArrayList<AssetHistory>();
		String assetStatus="IN USE";
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from AssetHistory ah where ah.assetRequest.assetRequestId=:assetRequestId and ah.assetStatus=:assetStatus";
			System.out.println("QUERY========"+queryString);
			Query query = session.createQuery(queryString);
			System.out.println("======query==========="+query.getQueryString().toString());
			/*System.out.println("======query==========="+query.getNamedParameters());
			System.out.println("======query==========="+query.getNamedParameters());
			*/
			query.setCacheable(false).setLong("assetRequestId", assetRequestId).setString("assetStatus", assetStatus);			
			assetHistoryDetails =(List<AssetHistory>) query.list();
			session.getTransaction().commit();
			return assetHistoryDetails;	
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}		
	}
	
	 public static void main(String args[]){
			//System.out.println(new AssetRequestDAO().getAllAssignedAssets(1l));		
			List<AssetHistory> assetDetailsList =new AssetHistoryDAO().getAssetHistoryDetailsByAssetRequest(6l);
			for(AssetHistory as:assetDetailsList){
				System.out.println("=========DAO====================");
				System.out.println("ASSET TYPE ==="+as.getAssetDetails().getAssetType());
				System.out.println("ASSET CODE ===="+as.getAssetDetails().getAssetReferenceCode());
			}
	}
	 


}
